package com.ntschy.sys.service.impl;

import cn.hutool.core.util.IdUtil;
import com.ntschy.common.config.ProjectConfig;
import com.ntschy.common.constant.HttpStatus;
import com.ntschy.common.core.AjaxResult;
import com.ntschy.common.core.entity.enums.SysBusinessType;
import com.ntschy.common.utils.file.FileUploadUtils;
import com.ntschy.sys.entity.dataobject.SysFileUp;
import com.ntschy.sys.mapper.SysFileUpMapper;
import com.ntschy.sys.service.ISysFileUpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author ezreal_geng
 */
@Service
public class SysFileUpServiceImpl implements ISysFileUpService {


    @Autowired
    private SysFileUpMapper fileUpMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addFileUp(MultipartFile file, SysBusinessType businessType) {

        try {
            // 上传文件路径
            String filePath = ProjectConfig.getUpload();
            String fileName = file.getOriginalFilename();
            // 上传并返回新文件名称
            String fileUrl = FileUploadUtils.upload(filePath, file);

            SysFileUp fileUp = new SysFileUp();
            fileUp.setId(IdUtil.fastUUID());
            fileUp.setFileName(fileName);
            fileUp.setFilePath(fileUrl);
            fileUp.setBusinessType(businessType);
            fileUpMapper.insert(fileUp);

            return AjaxResult.success("上传成功",fileUp);
        } catch (Exception e) {
            return AjaxResult.error(HttpStatus.FILE, e.getMessage());
        }
    }

    @Override
    public int updateFileUp(SysFileUp fileUp) {
        return fileUpMapper.updateById(fileUp);
    }

    @Override
    public int deleteFileUp(String id) {
        return fileUpMapper.deleteById(id);
    }

}
